package com.shs.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shs.sys.common.*;
import com.shs.sys.entity.Permission;
import com.shs.sys.entity.User;
import com.shs.sys.service.PermissionService;
import com.shs.sys.service.RoleService;
import com.shs.sys.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: jxm
 * @Description: 菜单管理前端控制器
 * @Date: 2020/4/9 16:47
 * @Version: 1.0
 */
@RestController
@RequestMapping("menu")
public class MenuController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("loadIndexLetfMenuJson")
    public DataGridView loadIndexLetfMenuJson(PermissionVo permissionVo){
        User user = (User)WebUtils.getSession().getAttribute("user");
        List<Permission> list = null;
        //设置只能查询菜单
        QueryWrapper<Permission> wrapper = new QueryWrapper();
        wrapper.eq("type",Constants.TYPE_MENU);
        wrapper.eq("available",Constants.AVAILABLE_TRUE);
        //查询所有菜单
        if(user.getType() == Constants.USER_TYPE_SUPER){
            list = permissionService.list(wrapper);
        }else {
            //根据用户ID+角色+权限去查询 --todo
            Integer userId = user.getId();
            List<Integer> rids = roleService.queryUserRoleIdsByUid(userId);
            //根据角色id获取权限和菜单id
            Set<Integer> pids = new HashSet<>();
            for (Integer rid : rids) {
                List<Integer> permissionIds = roleService.queryRolePermissionIdsByRid(rid);
                pids.addAll(permissionIds);
            }
            //根据角色id查询菜单
            if(pids.size()>0){
                wrapper.in("id",pids);
                list = permissionService.list(wrapper);
            }else{
                list = new ArrayList<>();
            }
        }
        List<TreeNode> treeNodes=new ArrayList<>();
        for (Permission p : list) {
            Integer id=p.getId();
            Integer pid=p.getPid();
            String title=p.getTitle();
            String icon=p.getIcon();
            String href=p.getHref();
            Boolean spread = p.getOpen()==Constants.OPEN_TRUE ? true : false;
            treeNodes.add(new TreeNode(id,pid,title,icon,href,spread));
        }
        //构造层级关系
        List<TreeNode> list2 = TreeNodeBuilder.build(treeNodes, 1);
        return new DataGridView(list2);
    }

    /****************菜单管理开始****************/

    /**
     * 加载菜单管理左边的菜单树json
     * @param permissionVo
     * @return
     */
    @RequestMapping("loadMenuManagerLeftTreeJson")
    public DataGridView loadMenuManagerLeftTreeJson(PermissionVo permissionVo){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",Constants.TYPE_MENU);
        List<Permission> menus = permissionService.list(queryWrapper);
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission menu : menus) {
            Boolean spread = menu.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),spread));
        }
        return new DataGridView(treeNodes);
    }

    /**
     * 查询
     */
    @RequestMapping("loadAllMenu")
    public DataGridView loadAllMenu(PermissionVo vo){
        Page<Permission> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<Permission> wrapper = new QueryWrapper();
        wrapper.eq(vo.getId()!=null,"id",vo.getId()).or()
                .eq(vo.getId()!=null,"pid",vo.getId());
        wrapper.eq("type",Constants.TYPE_MENU);
        wrapper.like(StringUtils.isNotBlank(vo.getTitle()),"title",vo.getTitle());
        wrapper.orderByAsc("ordernum");
        permissionService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 获取菜单排序码
     */
    @RequestMapping("loadMenuMaxOrderNum")
    public Map<String,Object> loadMenuMaxOrderNum(){
        Map<String,Object> result = new HashMap<>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type","menu");
        queryWrapper.orderByDesc("ordernum");
        List<Permission> menus = permissionService.list(queryWrapper);
        if(null!=menus && menus.size()>0){
            result.put("value",menus.get(0).getOrdernum()+1);
        }else{
            result.put("value",1);
        }
        return result;
    }

    /**
     * 添加菜单
     */
    @RequestMapping("addMenu")
    public ResultObj addMenu(PermissionVo permissionVo){
        try {
            permissionVo.setType(Constants.TYPE_MENU);//设置添加类型
            permissionService.save(permissionVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改菜单
     */
    @RequestMapping("updateMenu")
    public ResultObj updateMenu(PermissionVo menuVo){
        try {
            permissionService.updateById(menuVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除
     */
    @RequestMapping("deleteMenu")
    public ResultObj deleteMenu(PermissionVo vo){
        try {
            permissionService.removeById(vo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 删除之前检查菜单是否还有其他子菜单
     */
    @RequestMapping("checkMenuHasChildrenNode")
    public Map<String,Object> checkMenuHasChildrenNode(Integer id){
        Map<String,Object> result = new HashMap<>();
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",id);
        List<Permission> menus = permissionService.list(wrapper);
        if(menus.size()>0){
            result.put("value",true);
        }else{
            result.put("value",false);
        }
        return  result;
    }

    /****************菜单管理结束****************/
}

